﻿using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text;

namespace DFGK_WMS.WebAPI.Tools
{
    public class WebSocketConnectManager
    {
        private ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>();
        /// <summary>
        /// 获取所有 WebSocket 连接
        /// </summary>
        /// <returns></returns>
        private ConcurrentDictionary<string, WebSocket> GetAllSockets() => _sockets;
        public async Task SendMsgToAllClients(string message)
        {
            var sockets = GetAllSockets();
            foreach (var socket in sockets)
            {
                if (socket.Value.State != WebSocketState.Open)
                {
                    RemoveSocket(socket.Key);
                    continue;
                }
                try
                {
                    await SendMessage(socket.Value, message);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        /// <summary>
        /// 根据id移除 WebSocket 连接
        /// </summary>
        /// <param name="id"></param>
        public void RemoveSocket(string id)
        {
            _sockets.TryRemove(id, out _);
            //logger.LogInformation($"ip地址{id}的WebSocket的连接断开");
        }
        private async Task SendMessage(WebSocket socket, string message)
        {
            try
            {
                var buffer = Encoding.UTF8.GetBytes(message);
                await socket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 添加新的 WebSocket 连接
        /// </summary>
        /// <param name="id"></param>
        /// <param name="socket"></param>
        public void AddSocket(string id, WebSocket socket)
        {
            _sockets.TryAdd(id, socket);
            //logger.LogInformation($"ip地址为[{id}]的客户端连接WebSocket成功");
        }
    }
}
